﻿using ReflectionStudio.Classes;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core;
using ReflectionStudio.Core.Events;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.IO;
using System.Windows;
using System.Windows.Xps.Packaging;
using System.Windows.Controls;
using System.Reflection;
namespace WPFExcelReport
{
    /// <summary>
    /// HelpDocument display xps help documents
    /// </summary>
    public partial class HelpDocument
    {
        ApplicationBase ApplicationBase;
        bool IsSetUp = false;
        public IntexReptServBLClient proxy;
        private Dictionary<string, object> dicParamater;
        public OracleConnection OracleDB;
        public DataSet dsParamaters;
        private string m_ActiveDocument = "";
        string current = "";
        public string ActiveDocument
        {
            get
            {
                return m_ActiveDocument;
            }
            set
            {
                if (current == value)
                    return;
                m_ActiveDocument = value;
                this.Name = value;
                Worker.RunWorkerAsync();
            }
        }
        /// <summary>
        /// Constructor
        /// </summary>
        public HelpDocument()
        {
            InitializeComponent();
            this.Name = "帮助";
        }
        public override void SetUp(Dictionary<string, object> dicParamater)
        {
            try
            {
                dicParamater["blBuildCellMastrix"] = false;
                base.SetUp(dicParamater);
                InitializeComponent();
                this.dicParamater = dicParamater;
                OracleDB = (OracleConnection)dicParamater["OracleDB"];
                proxy = (IntexReptServBLClient)dicParamater["proxy"];
                IsSetUp = true;
                ApplicationBase = (ApplicationBase)dicParamater["ApplicationBase"];
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (IsLoaded)
                    return;
                Worker.DoWork += new DoWorkEventHandler(bw_DoWork);
                Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
                IsLoaded = true;
                EventDispatcher.Instance.OnMessage += OnMessage;
                if (!IsSetUp)
                {
                    ApplicationBase = new ApplicationBase();
                    ApplicationBase.Load();
                    dicParamater = ApplicationBase.dicParamater;
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        public void OnMessage(object sender, MessageEventArgs e)
        {
            MessageEventType type= e.Info.Type;
            string key=e.Info.Details;
            if (type == MessageEventType.Help)
            {
                this.ActiveDocument = key;
            }
        } 
        #region ---------------------LOAD / SAVE--------------------- 
      
        /// <summary>
        /// Threaded loading
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            Tracer.Verbose("HelpDocument:bw_DoWork", "START");
            try
            {
                if (m_ActiveDocument == "")
                    return;
                string fileName = Path.Combine(PathHelper.ApplicationPath, @"Documents\" + m_ActiveDocument + ".xps");
                /*IDocumentDataContext ctx  = new HelpDocumentDataContext() { FullName = fileName };
                e.Result = ctx.Load();*/
                current = m_ActiveDocument;
            }
            catch (Exception all)
            {
                Tracer.Error("HelpDocument.bw_DoWork", all);
            }
            finally
            {
                Tracer.Verbose("HelpDocument:bw_DoWork", "END");
                m_ActiveDocument ="";
            }
        }
        private void Find(string text="")
        {
            object findToolbar = documentViewer1.Template.FindName("PART_FindToolBarHost", documentViewer1);
            if (findToolbar == null)
                return;
            if (text == "")
                return;
            try
            {
                FieldInfo findTextBoxFieldInfo = findToolbar.GetType().GetField("TextEditor", BindingFlags.NonPublic | BindingFlags.Instance);
                TextBox findTextBox = (TextBox)findTextBoxFieldInfo.GetValue(findToolbar);
                findTextBox.Text = text;
                FieldInfo findNextButtonFieldInfo = findToolbar.GetType().GetField("FindNextButton", BindingFlags.NonPublic | BindingFlags.Instance);
                Button findNextButton = (Button)findNextButtonFieldInfo.GetValue(findToolbar);
                findNextButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            }
            catch (Exception ex)
            { 
            }
        }

        /// <summary>
        /// Thread completed management
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            // First, handle the case where an exception was thrown.
            if (e.Error != null)
            {
                Tracer.Error("HelpDocument.bw_RunWorkerCompleted", e.Error);
            }
            else
            {
                Tracer.Verbose("HelpDocument:bw_RunWorkerCompleted", "START");
                try
                {
                    if (e.Result != null && e.Result is XpsDocument)
                    {
                        XpsDocument xps = (XpsDocument)e.Result;
                        documentViewer1.Document = xps.GetFixedDocumentSequence();
                        ContentData = xps;
                        Find("WD001");
                    }
                    WaitPanel.Stop();
                   
                }
                catch (Exception all)
                {
                    Tracer.Error("HelpDocument.bw_RunWorkerCompleted", all);
                }
                finally
                {
                    //Worker.DoWork -= bw_DoWork;
                    //Worker.RunWorkerCompleted -= bw_RunWorkerCompleted;
                    Tracer.Verbose("HelpDocument:bw_RunWorkerCompleted", "END");
                }
            }
        }
        #endregion
    }
}
